package com.briup.ptt.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 杰瑞
 * @date 2025/8/15
 */
public class JWTUtil {

    /**
     * 盐值
     */
    private static final String key = "briup";

    public static String createToken(String userId, Map<String, Object>  info){

        try {
            Algorithm algorithm = Algorithm.HMAC256(key);

            Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);

            String token = JWT.create().withAudience(userId)
                    .withClaim("info", info)
                    .withExpiresAt(date)
                    .sign(algorithm);
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(key);
            JWT.require(algorithm)
                    .build()
                    .verify(token);
            return true;
        } catch (JWTVerificationException e) {
            throw new RuntimeException("token异常，请重新获取");
        }
    }

    public static String getUserId(String token){
        return JWT.decode(token).getAudience().get(0);
    }

    public static Map<String, Object> getInfo(String token){
        return JWT.decode(token).getClaim("info").asMap();
    }

    public static void removeToken(String token) {

    }
}
